package com.aptemo.webetek.client.widgets.teams;

import java.util.ArrayList;

import com.aptemo.webetek.client.WebetekUserServiceAsync;
import com.aptemo.webetek.client.commands.GotAsynchCallback;
import com.aptemo.webetek.client.commands.impl.CreateTeamAction;
import com.aptemo.webetek.client.commands.impl.DeleteTeamAction;
import com.aptemo.webetek.client.commands.impl.GetTeamDetailsAction;
import com.aptemo.webetek.client.commands.impl.ModifyTeamAction;
import com.aptemo.webetek.client.commands.responses.ResponseStatus;
import com.aptemo.webetek.client.enums.EEditMode;
import com.aptemo.webetek.client.enums.EnumUserRole;
import com.aptemo.webetek.client.events.DecisionEvent;
import com.aptemo.webetek.client.events.DecisionHandler;
import com.aptemo.webetek.client.events.HasDecisionHandlers;
import com.aptemo.webetek.client.events.TeamAddedEvent;
import com.aptemo.webetek.client.events.TeamDeletedEvent;
import com.aptemo.webetek.client.events.TeamUpdatedEvent;
import com.aptemo.webetek.client.exceptions.BackendException.EErrorCodes;
import com.aptemo.webetek.client.mvp.BaseDisplay;
import com.aptemo.webetek.client.mvp.BasePresenter;
import com.aptemo.webetek.shared.TeamBean;
import com.aptemo.webetek.shared.UserBean;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HasWidgets;

public class UserGroupResumePresenter implements BasePresenter
{

	interface Display extends BaseDisplay
	{
		HasText getTitleField();

		HasText getInfoField();

		HasText getNameField();

		HasText getDescField();

		HasText getOwnerField();

		HasClickHandlers getSaveBtn();

		HasValue<Boolean> getPublicCheckbox();

		void setEditMode(EEditMode mode);

		void setPlayersList(ArrayList<UserBean> list);

		HasDecisionHandlers getDeleteConfirmationDialog();

		HasText getRulesField();

		String translate(String string);

		HasValue<String> getMinStake();

		HasValue<String> getMaxStake();

		HasValue<Boolean> getNotificationsCheckbox();

		String enterValidValue(String value);

		void setOwnerEmail(String email);

		HasText getSaveBtnTitle();

		void hideDeleteConfirmationDialog();
	}

	private Display					display;
	private HandlerManager			eventBus;
	private WebetekUserServiceAsync	rpcService;
	private String					teamId;
	protected UserBean				currentUser;
	private String					email;

	//
	public UserGroupResumePresenter(UserBean currentUser, Display view, HandlerManager eventBus, WebetekUserServiceAsync rpc, String id, String email)
	{
		this.display = view;
		this.eventBus = eventBus;
		this.rpcService = rpc;
		this.currentUser = currentUser;
		this.teamId = id;
		this.email = email;
	}

	private void loadData()
	{
		GetTeamDetailsAction action = new GetTeamDetailsAction(teamId);
		rpcService.invoke(action, new GotAsynchCallback<TeamBean>()
		{
			@Override
			public void onError(String message, EErrorCodes code)
			{
				display.getInfoField().setText("" + message);
			}

			@Override
			public void onSuccess(TeamBean result)
			{
				display.getInfoField().setText("");

				display.getTitleField().setText(result.getName());

				display.getNameField().setText(result.getName());
				display.getDescField().setText(result.getDescription());
				display.getPublicCheckbox().setValue(result.isPublic());
				display.getRulesField().setText(result.getTeamRules());
				display.getMinStake().setValue(result.getMinStake() + "");
				display.getMaxStake().setValue(result.getMaxStake() + "");
				display.getNotificationsCheckbox().setValue(result.isNotifications());
				display.getOwnerField().setText(result.getOwnerEmail());

				// loadUserDetails();
				if (currentUser != null)
				{
					EnumUserRole role = currentUser.getRole();
					switch (role)
					{
						case ADMIN:
						case EDITOR:
							display.setEditMode(EEditMode.EEDIT);
							break;
						default:
							display.setEditMode(EEditMode.EREADONLY);
					}
				}
			}

		});

	}

	@Override
	public void go(HasWidgets container)
	{
		bind();

		container.clear();
		container.add(display.getDisplay());

		if ((null != teamId) && (!teamId.isEmpty()))
		{
			loadData();
		}
		else
		{
			// display.getInfoField().setText("Creating new team...");
			display.setEditMode(EEditMode.EADD);

			display.getSaveBtnTitle().setText(display.translate("sendNewTeamRequest"));

			if (currentUser != null)
			{
				display.setOwnerEmail(currentUser.getEmail());
			}
			else
			{
				display.setOwnerEmail(email);
			}
			// display.getOwnerField().setText(user.getEmail());
		}

	}

	private void bind()
	{
		display.getSaveBtn().addClickHandler(new ClickHandler()
		{

			@Override
			public void onClick(ClickEvent event)
			{
				doSave();
			}
		});

		display.getDeleteConfirmationDialog().addDecisionHandler(new DecisionHandler()
		{

			@Override
			public void onConfirmation(DecisionEvent event)
			{
				doDelete();
			}
		});

	}

	private void doDelete()
	{
		display.getInfoField().setText(display.translate("deleting"));

		DeleteTeamAction action = new DeleteTeamAction(teamId);

		rpcService.invoke(action, new GotAsynchCallback<ResponseStatus>()
		{

			@Override
			public void onSuccess(ResponseStatus status)
			{
				display.getInfoField().setText(display.translate("success"));
				display.hideDeleteConfirmationDialog();
				eventBus.fireEvent(new TeamDeletedEvent(teamId));
			}

			@Override
			public void onError(String message, EErrorCodes code)
			{
				display.getInfoField().setText(message);
			}
		});
	}

	private void doSave()
	{
		display.getInfoField().setText(display.translate("saving"));

		// check fields...
		if (display.getNameField().getText().isEmpty())
		{
			// display.getInfoField().setText(Webetek.getMessages().enterValidValue(Webetek.getConstants().teamName()));
			display.getInfoField().setText(display.enterValidValue("teamName"));
			return;
		}
		else if (display.getDescField().getText().isEmpty())
		{

			// display.getInfoField().setText(Webetek.getMessages().enterValidValue(Webetek.getConstants().teamDescription()));
			display.getInfoField().setText(display.enterValidValue("teamDescription"));
			return;
		}

		TeamBean bean = new TeamBean(display.getNameField().getText());
		bean.setKey(teamId);
		bean.setDescription(display.getDescField().getText());
		bean.setOwnerEmail(display.getOwnerField().getText());
		bean.setPublic(display.getPublicCheckbox().getValue());
		bean.setTeamRules(display.getRulesField().getText());
		bean.setPlaceBetNotifications(display.getNotificationsCheckbox().getValue());

		String mins = display.getMinStake().getValue();
		String maxs = display.getMaxStake().getValue();

		Double minStake = 0.0;
		Double maxStake = Double.POSITIVE_INFINITY;
		try
		{
			minStake = Double.parseDouble(mins);
			maxStake = Double.parseDouble(maxs);
		}
		catch (NumberFormatException e)
		{
			e.printStackTrace();
		}
		bean.setMinStake(minStake);
		bean.setMaxStake(maxStake);

		if ((null != teamId) && (!teamId.isEmpty()))
		{
			modifyTeam(bean);
		}
		else
		{
			createTeam(bean);
		}

	}

	private void createTeam(TeamBean bean)
	{
		CreateTeamAction action = new CreateTeamAction(bean);
		rpcService.invoke(action, new GotAsynchCallback<TeamBean>()
		{

			@Override
			public void onError(String message, EErrorCodes code)
			{
				display.getInfoField().setText(message);
			}

			@Override
			public void onSuccess(TeamBean result)
			{
				display.getInfoField().setText(display.translate("addSuccess"));
				eventBus.fireEvent(new TeamAddedEvent(result.getId()));
			}

		});
	}

	private void modifyTeam(TeamBean bean)
	{
		// this.teamid, display.getNameField().getText(),
		// display.getDescField().getText(), display.getOwnerField()
		// .getText(), display.getPublicCheckbox().getValue(),
		// display.getRulesField().getText(), minStake, maxStake,
		// display.getNotificationsCheckbox().getValue()
		//		
		rpcService.invoke(new ModifyTeamAction(bean), new GotAsynchCallback<TeamBean>()
		{

			@Override
			public void onError(String message, EErrorCodes code)
			{
				//
				display.getInfoField().setText(message);
			}

			@Override
			public void onSuccess(TeamBean result)
			{
				display.getInfoField().setText(display.translate("modifySuccess"));

				eventBus.fireEvent(new TeamUpdatedEvent(teamId));
			}

		});

	}
}
